package kassiopeia.agent.seda.threads;

import kassiopeia.agent.alerting.Alerting;
import kassiopeia.agent.seda.event.EventQueue;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

public class DefaultPoolSizeStrategy implements PoolSizeStrategy {

    private Logger log = Logger.getLogger(DefaultPoolSizeStrategy.class);
    private int stagePoolSizeLimit;
    private int sleepPeriod;

    @Autowired
    private Alerting alerting;

    @Override
    public void managePoolSize(StagePool pool, EventQueue queue) {
        int poolSize = pool.size();
        int queueSize = queue.size();
        int newStagePoolSize;

        if (queueSize > poolSize) {
            newStagePoolSize = Math.min(queueSize, stagePoolSizeLimit);
            pool.setSize(newStagePoolSize);

        } else if (queueSize < poolSize && poolSize > 1) {
            newStagePoolSize = Math.max(1, queueSize);
            pool.setSize(newStagePoolSize);
        }
    }

    @Override
    public synchronized int getStagePoolSizeLimit() {
        return stagePoolSizeLimit;
    }

    @Override
    public synchronized int getSleepPeriod() {
        return sleepPeriod;
    }

    @Override
    public synchronized void setStagePoolSizeLimit(int stagePoolSizeLimit) {
        this.stagePoolSizeLimit = stagePoolSizeLimit;
    }

    @Override
    public synchronized void setSleepPeriod(int sleepPeriod) {
        this.sleepPeriod = sleepPeriod;
    }
}
